package com.lifeverse.service;

import com.lifeverse.event.GroupDecisionEvent;
import com.lifeverse.event.LifeEntityEvent;
import com.lifeverse.event.LifeEntityInteractionEvent;
import com.lifeverse.event.NetworkHealthEvent;
import com.lifeverse.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

/**
 * 事件监听服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EventListener {
    
    private final LifeEntityRelationshipService relationshipService;
    private final NetworkHealthMonitor networkHealthMonitor;
    
    /**
     * 监听生命体互动事件
     */
    @KafkaListener(topics = EventPublisher.LIFE_ENTITY_INTERACTION_TOPIC, 
                   groupId = "life-entity-interaction-group")
    public void handleLifeEntityInteractionEvent(
            @Payload String eventJson,
            @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
            @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
            @Header(KafkaHeaders.OFFSET) long offset,
            Acknowledgment acknowledgment) {
        
        try {
            log.debug("接收到生命体互动事件: topic={}, partition={}, offset={}", topic, partition, offset);
            
            LifeEntityInteractionEvent event = JsonUtils.fromJson(eventJson, LifeEntityInteractionEvent.class);
            
            // 处理互动事件
            processInteractionEvent(event);
            
            // 手动确认消息
            acknowledgment.acknowledge();
            
            log.debug("生命体互动事件处理完成: eventId={}, interactionType={}", 
                    event.getEventId(), event.getInteractionType());
            
        } catch (Exception e) {
            log.error("处理生命体互动事件失败: topic={}, partition={}, offset={}", topic, partition, offset, e);
            // 这里可以实现重试逻辑或将消息发送到死信队列
        }
    }
    
    /**
     * 监听网络健康事件
     */
    @KafkaListener(topics = EventPublisher.NETWORK_HEALTH_TOPIC, 
                   groupId = "network-health-group")
    public void handleNetworkHealthEvent(
            @Payload String eventJson,
            @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
            @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
            @Header(KafkaHeaders.OFFSET) long offset,
            Acknowledgment acknowledgment) {
        
        try {
            log.debug("接收到网络健康事件: topic={}, partition={}, offset={}", topic, partition, offset);
            
            NetworkHealthEvent event = JsonUtils.fromJson(eventJson, NetworkHealthEvent.class);
            
            // 处理网络健康事件
            processNetworkHealthEvent(event);
            
            // 手动确认消息
            acknowledgment.acknowledge();
            
            log.debug("网络健康事件处理完成: eventId={}, healthStatus={}", 
                    event.getEventId(), event.getHealthStatus());
            
        } catch (Exception e) {
            log.error("处理网络健康事件失败: topic={}, partition={}, offset={}", topic, partition, offset, e);
        }
    }
    
    /**
     * 监听群体决策事件
     */
    @KafkaListener(topics = EventPublisher.GROUP_DECISION_TOPIC, 
                   groupId = "group-decision-group")
    public void handleGroupDecisionEvent(
            @Payload String eventJson,
            @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
            @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
            @Header(KafkaHeaders.OFFSET) long offset,
            Acknowledgment acknowledgment) {
        
        try {
            log.debug("接收到群体决策事件: topic={}, partition={}, offset={}", topic, partition, offset);
            
            GroupDecisionEvent event = JsonUtils.fromJson(eventJson, GroupDecisionEvent.class);
            
            // 处理群体决策事件
            processGroupDecisionEvent(event);
            
            // 手动确认消息
            acknowledgment.acknowledge();
            
            log.debug("群体决策事件处理完成: eventId={}, decisionStatus={}", 
                    event.getEventId(), event.getDecisionStatus());
            
        } catch (Exception e) {
            log.error("处理群体决策事件失败: topic={}, partition={}, offset={}", topic, partition, offset, e);
        }
    }
    
    /**
     * 监听意识状态变化事件
     */
    @KafkaListener(topics = EventPublisher.CONSCIOUSNESS_STATE_TOPIC, 
                   groupId = "consciousness-state-group")
    public void handleConsciousnessStateEvent(
            @Payload String eventJson,
            @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
            @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
            @Header(KafkaHeaders.OFFSET) long offset,
            Acknowledgment acknowledgment) {
        
        try {
            log.debug("接收到意识状态事件: topic={}, partition={}, offset={}", topic, partition, offset);
            
            LifeEntityEvent event = JsonUtils.fromJson(eventJson, LifeEntityEvent.class);
            
            // 处理意识状态事件
            processConsciousnessStateEvent(event);
            
            // 手动确认消息
            acknowledgment.acknowledge();
            
            log.debug("意识状态事件处理完成: eventId={}", event.getEventId());
            
        } catch (Exception e) {
            log.error("处理意识状态事件失败: topic={}, partition={}, offset={}", topic, partition, offset, e);
        }
    }
    
    /**
     * 监听系统警报事件
     */
    @KafkaListener(topics = EventPublisher.SYSTEM_ALERT_TOPIC, 
                   groupId = "system-alert-group")
    public void handleSystemAlertEvent(
            @Payload String eventJson,
            @Header(KafkaHeaders.RECEIVED_TOPIC) String topic,
            @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition,
            @Header(KafkaHeaders.OFFSET) long offset,
            Acknowledgment acknowledgment) {
        
        try {
            log.debug("接收到系统警报事件: topic={}, partition={}, offset={}", topic, partition, offset);
            
            LifeEntityEvent event = JsonUtils.fromJson(eventJson, LifeEntityEvent.class);
            
            // 处理系统警报事件
            processSystemAlertEvent(event);
            
            // 手动确认消息
            acknowledgment.acknowledge();
            
            log.debug("系统警报事件处理完成: eventId={}", event.getEventId());
            
        } catch (Exception e) {
            log.error("处理系统警报事件失败: topic={}, partition={}, offset={}", topic, partition, offset, e);
        }
    }
    
    /**
     * 处理生命体互动事件
     */
    private void processInteractionEvent(LifeEntityInteractionEvent event) {
        log.info("处理生命体互动事件: sourceId={}, targetId={}, type={}", 
                event.getSourceEntityId(), event.getTargetEntityId(), event.getInteractionType());
        
        try {
            // 更新关系的最后互动时间
            if (event.getRelationshipId() != null) {
                relationshipService.updateInteractionTime(event.getRelationshipId());
            }
            
            // 根据互动类型执行相应的业务逻辑
            switch (event.getInteractionType()) {
                case COLLABORATION:
                    handleCollaborationInteraction(event);
                    break;
                case COMMUNICATION:
                    handleCommunicationInteraction(event);
                    break;
                case KNOWLEDGE_SHARING:
                    handleKnowledgeSharingInteraction(event);
                    break;
                case RESOURCE_EXCHANGE:
                    handleResourceExchangeInteraction(event);
                    break;
                case DECISION_MAKING:
                    handleDecisionMakingInteraction(event);
                    break;
                case CONFLICT_RESOLUTION:
                    handleConflictResolutionInteraction(event);
                    break;
                default:
                    log.debug("处理通用互动事件: {}", event.getInteractionType());
                    break;
            }
            
            // 更新网络活跃度
            updateNetworkActivity(event);
            
        } catch (Exception e) {
            log.error("处理互动事件时发生异常: eventId={}", event.getEventId(), e);
        }
    }
    
    /**
     * 处理网络健康事件
     */
    private void processNetworkHealthEvent(NetworkHealthEvent event) {
        log.info("处理网络健康事件: networkType={}, healthStatus={}, alertLevel={}", 
                event.getNetworkType(), event.getHealthStatus(), event.getAlertLevel());
        
        try {
            // 检查是否需要触发警报
            if (event.getAlertLevel() != null && event.getAlertLevel() >= 3) {
                handleNetworkHealthAlert(event);
            }
            
            // 检查健康状态变化
            if (event.getChangeType() != null) {
                switch (event.getChangeType()) {
                    case CRITICAL:
                        handleCriticalHealthChange(event);
                        break;
                    case DEGRADED:
                        handleHealthDegradation(event);
                        break;
                    case IMPROVED:
                        handleHealthImprovement(event);
                        break;
                    case RECOVERED:
                        handleHealthRecovery(event);
                        break;
                    default:
                        break;
                }
            }
            
        } catch (Exception e) {
            log.error("处理网络健康事件时发生异常: eventId={}", event.getEventId(), e);
        }
    }
    
    /**
     * 处理群体决策事件
     */
    private void processGroupDecisionEvent(GroupDecisionEvent event) {
        log.info("处理群体决策事件: groupId={}, decisionId={}, eventType={}", 
                event.getGroupId(), event.getDecisionId(), event.getEventSubType());
        
        try {
            // 根据决策事件类型执行相应的业务逻辑
            switch (event.getEventSubType()) {
                case PROPOSED:
                    handleDecisionProposed(event);
                    break;
                case VOTING_STARTED:
                    handleVotingStarted(event);
                    break;
                case VOTE_CAST:
                    handleVoteCast(event);
                    break;
                case VOTING_ENDED:
                    handleVotingEnded(event);
                    break;
                case APPROVED:
                    handleDecisionApproved(event);
                    break;
                case REJECTED:
                    handleDecisionRejected(event);
                    break;
                case IMPLEMENTED:
                    handleDecisionImplemented(event);
                    break;
                case CANCELLED:
                    handleDecisionCancelled(event);
                    break;
                default:
                    break;
            }
            
        } catch (Exception e) {
            log.error("处理群体决策事件时发生异常: eventId={}", event.getEventId(), e);
        }
    }
    
    /**
     * 处理意识状态事件
     */
    private void processConsciousnessStateEvent(LifeEntityEvent event) {
        log.info("处理意识状态事件: sourceEntityId={}", event.getSourceEntityId());
        
        try {
            // 这里可以添加意识状态变化的处理逻辑
            // 例如：更新生命体的意识状态、触发相关的业务流程等
            
        } catch (Exception e) {
            log.error("处理意识状态事件时发生异常: eventId={}", event.getEventId(), e);
        }
    }
    
    /**
     * 处理系统警报事件
     */
    private void processSystemAlertEvent(LifeEntityEvent event) {
        log.info("处理系统警报事件: eventType={}, priority={}", event.getEventType(), event.getPriority());
        
        try {
            // 根据事件类型和优先级执行相应的处理逻辑
            if (event.getPriority().getLevel() >= LifeEntityEvent.EventPriority.HIGH.getLevel()) {
                // 高优先级事件的处理
                handleHighPriorityAlert(event);
            }
            
            // 记录警报事件
            logAlertEvent(event);
            
        } catch (Exception e) {
            log.error("处理系统警报事件时发生异常: eventId={}", event.getEventId(), e);
        }
    }
    
    // 以下是各种具体的事件处理方法
    
    private void handleCollaborationInteraction(LifeEntityInteractionEvent event) {
        log.debug("处理协作互动: {}", event.getEventId());
        // 协作互动的具体处理逻辑
    }
    
    private void handleCommunicationInteraction(LifeEntityInteractionEvent event) {
        log.debug("处理通信互动: {}", event.getEventId());
        // 通信互动的具体处理逻辑
    }
    
    private void handleKnowledgeSharingInteraction(LifeEntityInteractionEvent event) {
        log.debug("处理知识分享互动: {}", event.getEventId());
        // 知识分享的具体处理逻辑
    }
    
    private void handleResourceExchangeInteraction(LifeEntityInteractionEvent event) {
        log.debug("处理资源交换互动: {}", event.getEventId());
        // 资源交换的具体处理逻辑
    }
    
    private void handleDecisionMakingInteraction(LifeEntityInteractionEvent event) {
        log.debug("处理决策制定互动: {}", event.getEventId());
        // 决策制定的具体处理逻辑
    }
    
    private void handleConflictResolutionInteraction(LifeEntityInteractionEvent event) {
        log.debug("处理冲突解决互动: {}", event.getEventId());
        // 冲突解决的具体处理逻辑
    }
    
    private void updateNetworkActivity(LifeEntityInteractionEvent event) {
        log.debug("更新网络活跃度: {}", event.getEventId());
        // 更新网络活跃度的逻辑
    }
    
    private void handleNetworkHealthAlert(NetworkHealthEvent event) {
        log.warn("处理网络健康警报: networkType={}, healthScore={}", 
                event.getNetworkType(), event.getHealthScore());
        // 网络健康警报的处理逻辑
    }
    
    private void handleCriticalHealthChange(NetworkHealthEvent event) {
        log.error("处理关键健康状态变化: {}", event.getEventId());
        // 关键健康状态变化的处理逻辑
    }
    
    private void handleHealthDegradation(NetworkHealthEvent event) {
        log.warn("处理健康状态恶化: {}", event.getEventId());
        // 健康状态恶化的处理逻辑
    }
    
    private void handleHealthImprovement(NetworkHealthEvent event) {
        log.info("处理健康状态改善: {}", event.getEventId());
        // 健康状态改善的处理逻辑
    }
    
    private void handleHealthRecovery(NetworkHealthEvent event) {
        log.info("处理健康状态恢复: {}", event.getEventId());
        // 健康状态恢复的处理逻辑
    }
    
    private void handleDecisionProposed(GroupDecisionEvent event) {
        log.info("处理决策提议: decisionId={}", event.getDecisionId());
        // 决策提议的处理逻辑
    }
    
    private void handleVotingStarted(GroupDecisionEvent event) {
        log.info("处理投票开始: decisionId={}", event.getDecisionId());
        // 投票开始的处理逻辑
    }
    
    private void handleVoteCast(GroupDecisionEvent event) {
        log.debug("处理投票: decisionId={}", event.getDecisionId());
        // 投票的处理逻辑
    }
    
    private void handleVotingEnded(GroupDecisionEvent event) {
        log.info("处理投票结束: decisionId={}", event.getDecisionId());
        // 投票结束的处理逻辑
    }
    
    private void handleDecisionApproved(GroupDecisionEvent event) {
        log.info("处理决策通过: decisionId={}", event.getDecisionId());
        // 决策通过的处理逻辑
    }
    
    private void handleDecisionRejected(GroupDecisionEvent event) {
        log.info("处理决策拒绝: decisionId={}", event.getDecisionId());
        // 决策拒绝的处理逻辑
    }
    
    private void handleDecisionImplemented(GroupDecisionEvent event) {
        log.info("处理决策实施: decisionId={}", event.getDecisionId());
        // 决策实施的处理逻辑
    }
    
    private void handleDecisionCancelled(GroupDecisionEvent event) {
        log.info("处理决策取消: decisionId={}", event.getDecisionId());
        // 决策取消的处理逻辑
    }
    
    private void handleHighPriorityAlert(LifeEntityEvent event) {
        log.warn("处理高优先级警报: eventType={}, priority={}", event.getEventType(), event.getPriority());
        // 高优先级警报的处理逻辑
    }
    
    private void logAlertEvent(LifeEntityEvent event) {
        log.info("记录警报事件: eventId={}, eventType={}, priority={}", 
                event.getEventId(), event.getEventType(), event.getPriority());
        // 警报事件记录的逻辑
    }
}